<?php

namespace App\Http\Controllers\User;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Task;
use App\Models\TaskReply;
use App\Models\User;
use App\Models\TaskProcess;
use App\Models\TaskComment;
use App\Models\TaskService;
use App\Models\Service;
use App\Repos\TaskRepo;
use App\Repos\DepartRepo;
use Session;
use DB;
use App\Services\Wechat;

class TaskController extends Controller
{
    public function index( Request $request)
    {
        $wechat_user =  session('wechat.oauth_user.default');
        $where = $param = [];

        $query = Task::query();
        $user  = User::where('openid',$wechat_user->id)->first();
        if(object_get($user,'role_id',500)==500) {
            $where['openid'] = $wechat_user->id;
        } elseif(object_get($user,'role_id')==1) {
            $task_ids = TaskProcess::where('worker_openid',$wechat_user->id)->pluck('task_id');
            $query = $query->whereIn('id',$task_ids);
        }


        
        
        
        if ($request->status) {
            $where['status'] = intval($request->status);
        }

        
    	$query = $query->where($where);
        if($request->keyword) {
            $query = $query->where('title','like','%'.$request->keyword.'%');
        }

        $list = $query->orderBy('created_at','desc')
                    ->paginate(5);
        $status = $this->taskStatus();

        $map = [];         
        $countQuery = Task::query();
        if(object_get($user,'role_id',500) == 500) {
            $map['openid'] = $wechat_user->id;
            $done    = Task::where('status',100)->where($map)->count(); 
            $wait    = Task::where('status',1)->where($map)->count();
            $process = Task::where('status',50)->where($map)->count();      
            $total   = Task::where($map)->count();
            
           
        } elseif(object_get($user,'role_id')==1) {
            $task_ids = TaskProcess::where('worker_openid',$wechat_user->id)->pluck('task_id');
            $done    = Task::where('status',100)->whereIn('id',$task_ids)->count(); 
            $wait    = Task::where('status',1)->whereIn('id',$task_ids)->count();
            $process = Task::where('status',50)->whereIn('id',$task_ids)->count();        
            $total   = Task::whereIn('id',$task_ids)->count();
           
        } else {
            $done    = Task::where('status',100)->count(); 
            $wait    = Task::where('status',1)->count();
            $process = Task::where('status',50)->count();        
            $total   = Task::count();
        }
          

                   
        return view('hrs.task.index',compact('list','status','param','wait','process','done','total'));
        
    }

    public function create()
    {
        if (object_get(session('user'),'role_id') != self::EMPLOYEE) {
            //echo '此功能暂不管理员开放';die;
        }
    	$cates = Category::select('id','name')->get();
        $departs = DepartRepo::get();
        $serviceTimes = $this->serviceTime();
    	return view('hrs.task.add',compact('cates','departs','serviceTimes'));
    }	

    public function save(Request $request)
    {
        //dd($request->all());
    	$rs['status'] = 'danger';      
        $data         = $request->except(['_token','thumb','service_time2','service_time1']);    

        DB::beginTransaction();
        try{
           $wechat_user    =  session('wechat.oauth_user.default');
           
           $data['userinfo'] = json_encode(Wechat::getUserInfo($wechat_user->id));
           $data['openid'] = $wechat_user->id;
           $code = date('Ymdhis').str_random(3);
           if(object_get($request,'thumb')){
            $extension = $request->thumb->extension();
            $filename = $code.'.'.$extension;
            $request->thumb->storeAs('public/images',$filename);
            $data['thumb']  = '/storage/images/'.$filename; 
           } 
           
           $data['service_time'] = $request->service_time1.' '.$request->service_time2;  
           $data['status']   =1 ;
           $data['code']     = $code;
           $flag = Task::create($data);

            
            if(!$flag) {
                DB::rollBack();
                return back()->with($rs);
            } 
            DB::commit();
        } catch(\Exception $e) {
            DB::rollBack();
            $rs['msg'] = $e->getMessage();
            return back()->withInput()->with('rs',$rs);
        }
    	
        
        $rs['status'] = 'success';
        $rs['msg']    = '工单提交成功';

        try {
           // 推送消息
            // 1 推送给提交者
            $msg['first']      = '您提交的新工单已生成';
            $msg['task_id']    = $flag->id;
            $msg['openid']     = $data['openid'];
            $msg['code']       = $data['code'];
            $msg['cate_name']   = object_get($flag,'category.name') ;
            $msg['service_time'] = $request->service_time1.' '.$request->service_time2;  
            $msg['address']    = object_get($flag,'depart.name').$data['gatenum'];
            $msg['remark']     = $data['remark'];
            $msg['mobile']     = $data['mobile'];
            $msg['memo']     = '请等待管理人员派单';
           
           

            Wechat::tempNewTask($msg);

            // 推送给管理员
            $managers = User::where('role_id',100)->get();
            foreach ($managers as $k => $v) {
                if(empty($v->openid)) continue;     
                $msg2['first']  = '您有新的报修信息到达，请及时处理！';
                $msg2['openid'] = $v->openid; //此处需要改为物业人员的openid
                $msg2['customer_name'] = $data['customer_name'];
                $msg2['title']   = $data['title'];
                $msg2['mobile']  = $data['mobile'];
                $msg2['remark']  = $data['remark'];
                $msg2['memo']    ='点击详情处理报修。';
                $msg2['address'] = object_get($flag,'depart.name').$data['gatenum']; 
 
                $msg2['task_id'] = $flag->id;
                Wechat::tempNoticeToManager($msg2);          
            } 
        } catch (\Exception $e) {
            $rs['msg']    = $e->getMessage();
        }
        
        return redirect('user/task')->with('rs',$rs);    
       // return back()->withInput()->with('rs',$rs);

    }

    

  

    

  

    public function delete($id) 
    {
        $rs['status'] = 'danger';
        $flag = Task::destroy($id);
        if($flag) {
            $rs['status'] = 'success';
            $rs['msg']    = '删除成功';
            return back()->with($rs);
        }
        $rs['msg'] = '删除失败';
        return back()->with($rs);
    }


    public function show($id)
    {
        $data = Task::withTrashed()->find($id);
        $comment = TaskComment::where('task_id',$id)->first();
        $workers = User::where('role_id',1)->get();
        $wechat_user =  session('wechat.oauth_user.default');
        $user = User::where('openid',$wechat_user->id)->first();
        $process = TaskProcess::where(['task_id'=>$id])->get();
        $user_openid = $wechat_user->id;
        $point_arr = $this->commentPoint();
        $services = Service::get();
        return view('hrs.task.show',compact('data','workers','user','comment','point_arr','services','user_openid','process'));
    }

    public function edit($id)
    {
        $data = Task::find($id);
        if ($data->status != self::WAIT_STATUS) {
            $rs['msg'] = '工单不可修改';
            return back()->withInput()->with('rs',$rs);
        }
        $cates = Category::select('id','name')->get();
        
        return view('hrs.task.edit',compact('data','cates'));
    }

    public function update(Request $request)
    {
        $rs['status'] = 'danger';
        if ($request->status != 0) {
            $rs['msg'] = '此任务不可修改';
            return back()->withInput()->with('rs',$rs);
        }
        
        
        

      

        $data['seller_id']      = session('seller')->id;
        $data['status']         = 0; //任务都是需要审核的
        $data['valid_num']      = $data['num'];
        $data['total_money']    = $totalMoney;
        $data['platform_money'] = $platform_money;

       
        
        $flag = Task::where(['id'=>$request->id])->update($data);

           
            
        if(!$flag) {
            $rs['msg']    = '任务修改失败，请耐心等待审核';   
            return back()->with($rs);
        } 
       
        
      
        $rs['status'] = 'success';
        $rs['msg']    = '任务修改成功，请耐心等待审核';
        return back()->withInput()->with('rs',$rs);
    }

    public function reply(Request $request)
    {
        $rs['status'] = 'danger';
       
        $data = $request->except(['_token']);
        $data['from_user_id'] = session('user')->id;
        if($data['status'] == 50) {
            $data['msg'] .= ' 工单状态改变，当前状态为处理中';
        } elseif($data['status'] == 100) {
            $data['msg'] .= ' 工单状态改变，当前状态为已完结';
        } 
        $flag = TaskRepo::replay($data);
        //dd($flag);
        if($flag['status'] == true) {
            $rs['status'] = 'success';
            $rs['msg'] = '操作成功';
            return back()->with('rs',$rs);
        } else {
            $rs['status'] = 'danger';
            $rs['msg'] = $flag['msg'];
            return back()->with('rs',$rs);
        }

        
        return back()->with('rs',$rs);
    }

    public function process(Request $request)
    {
        
        $rs['status'] = 'danger';
        $rs['msg']    = '操作成功';
        $wechat_user =  session('wechat.oauth_user.default');
        $worker = User::find($request->worker_id);
        $task   = Task::find($request->task_id);

        $data = $request->except(['_token']);
        $data['worker_openid'] = $worker->openid; 
        $data['status'] = 50;  
        $data['creater_openid'] = $wechat_user->id;    
        $flag = TaskProcess::create($data);

        Task::where('id',$data['task_id'])->update(['status'=>50]);


        // 推送消息
         $msg2['first']  = '您有新的报修信息到达，请及时处理！';
        $msg2['openid'] = $worker->openid; //此处需要改为物业人员的openid
        $msg2['customer_name'] = $task['customer_name'];
        $msg2['title']   = $task['title'];
        $msg2['mobile']  = $task['mobile'];
        $msg2['remark']  = $data['remark'];
        $msg2['memo']    ='点击查看详情。'; 
        $msg2['task_id'] = $data['task_id'];
        Wechat::tempNoticeToManager($msg2);  

        if($flag == true) {
            $rs['status'] = 'success';
            $rs['msg'] = '操作成功';
            return back()->with('rs',$rs);
        } 
        return back()->with('rs',$rs);
        
    }

    // 报价信息
    public function processPrice(Request $request)
    {
        $rs['status'] = 'danger';
        $rs['msg']    = '操作失败';
        $data = $request->except(['_token']);
        $wechat_user =  session('wechat.oauth_user.default');
        $data['worker_openid'] = $wechat_user->id;
        $data['status'] = 0;

       

        $flag = TaskService::create($data);
        $task = Task::find($data['task_id']);
        $task->status = 75;
        $task->save();
        
        $process = array_only($data,['task_id','worker_openid','status']);
        $user = User::where('openid',$wechat_user->id)->first();
        $process['worker_id']      = $user->id;
        $process['creater_openid'] = $wechat_user->id;
        $process['remark'] = '报价：'.$data['service_name'].','.$data['service_price'];
        $process['status'] = 75;
        TaskProcess::create($process);

        // 推送消息
        $msg['openid']        = $data['task_openid'];
        $msg['service_price'] = $data['service_price'];
        $msg['service_name']  = $data['service_name'];
        $msg['code']          = $task->code;
        $msg['id']       = $flag->id;
        Wechat::tempPrice($msg);



        if($flag) {
            $rs['status'] = 'success';
            $rs['msg'] = '操作成功';
            return back()->with('rs',$rs);
        }
        return back()->with('rs',$rs);
    }

    /**
     * 工单报价详情
     */
    public function priceDetail($id)
    {
        $price = TaskService::find($id);
        $task = Task::find($price->task_id);
        return view('hrs.task.price',compact('price','task'));
    }

    /**
     * 用户确认工单费用
     */
    public function priceConfirmed(Request $request)
    {
        $rs['status'] = 'danger';
        $rs['msg'] = '操作失败';
        $taskService = TaskService::find($request->task_service_id);
        $taskService->status = $request->status;
        $flag = $taskService->save();

        if($request->status == -1) {
            Task::where('id',$taskService->task_id)->update(['status'=>'-1']);
            $where['task_id'] = $taskService->task_id;
            $where['worker_openid'] = $taskService->worker_openid;
            $process = TaskProcess::where($where)->first()->toArray();
            $process['status'] = '-1';
            $process['remark'] = '用户拒绝付款';
            $process['creater_openid'] = $taskService->task_openid;
            TaskProcess::create($process);
        }

        if($flag == true) {
            $rs['status'] = 'success';
            $rs['msg'] = '操作成功';
            return redirect('user/task/show/'.$taskService->task_id)->with('rs',$rs);
        } 
        return redirect('user/task/show/'.$taskService->task_id)->with('rs',$rs);


    }

    public function processComplete(Request $request)
    {
        $rs['status'] = 'danger';
        $rs['msg']    = '操作失败';


        $wechat_user =  session('wechat.oauth_user.default');    
        $taskProcess = TaskProcess::where('task_id',$request->task_id)->first()->toArray(); 
        
        $taskProcess = array_except($taskProcess,['created_at','updated_at']);           
        $taskProcess['status'] = 100;  
        $taskProcess['creater_openid'] = $wechat_user->id;   
        
        $flag = TaskProcess::create($taskProcess);

        $task   = Task::find($request->task_id);
        $task->status = 100;
        $task->save();


        
        $worker = User::find($taskProcess['worker_id']);

        // 推送消息
        $msg['first']       = '您的报修已完成';
        $msg['openid']      = $task->openid; // 通知提交报修的用户
        $msg['address']     = object_get($task,'depart.name').','.$task->gatenum;
        $msg['cate_name']   = object_get($task,'category.name');
        $msg['worker_name'] = $worker->truename;       
        $msg['remark']    ='点击查看详情。'; 
        $msg['task_id']   = $task->id;
        Wechat::tempComplete($msg);  // 先推送给客户
        
        // 再推送给管理员
        $managers = User::where('role_id',100)->get();
        foreach ($managers as $k => $v) {
            if(empty($v->openid)) continue;    
            $msg2 = $msg;
            $msg2['openid'] = $v->openid;
            Wechat::tempComplete($msg2); 
        }

        if($flag == true) {
            $rs['status'] = 'success';
            $rs['msg'] = '操作成功';
            return back()->with('rs',$rs);
        } 
        return back()->with('rs',$rs);
        
    }


    public function comment(Request $request)
    {
        $point_arr = $this->commentPoint();
        $rs['status'] = 'danger';
        $rs['msg']    = '操作失败';
        $data = $request->except(['_token']);
        $wechat_user =  session('wechat.oauth_user.default');  
        $data['user_openid'] = $wechat_user->id;

        $taskProcess = TaskProcess::where(['task_id'=>$request->task_id])->first();

        // 如果是零分那么要打回给维修人员
        if($data['point']==0) {
            //dd($request->task_id);
            $task = Task::find($request->task_id);
            $task->status = 50;
            $ret = $task->save();
            //dd($ret);
            $flag = TaskProcess::where('id',$taskProcess->id)->update(['status'=>50]);
            // 推送消息
            $msg2['first']  = '您好，工单需要重新维修，请尽快前往！';
            $msg2['openid'] = $taskProcess->worker_openid; //此处需要改为物业人员的openid
            $msg2['customer_name'] = $task->customer_name;
            $msg2['address']   = object_get($task,'depart.name').$task->gatenum;
            $msg2['mobile']  = $task->mobile;
            $msg2['code']    = $task->code;
            $msg2['remark']  = $task->remark;
            $msg2['cate_name'] = object_get($task,'category.name');
            $msg2['service_time'] = $task->service_time;
            $msg2['title'] = $task->title;
            $msg2['memo']    ='点击查看详情。'; 
            $msg2['task_id'] = $task->id;
            Wechat::tempNoticeToManager($msg2);  

            if($ret) {
                $rs['status'] = 'success';
                $rs['msg'] = '操作成功';
                return back()->with('rs',$rs);
            } 
        }


        $data['worker_id'] = $taskProcess->worker_id;
        $data['remark'] = $point_arr[$data['point']];

        $flag = TaskComment::create($data);
        //dd($flag);
        if($flag) {
            $rs['status'] = 'success';
            $rs['msg'] = '操作成功';
            return back()->with('rs',$rs);
        } 

        
        return back()->with('rs',$rs);
    }

     /**
     * 退单
     */
    public function refund(Request $request)
    {
        $rs['status'] = 'danger';
        $rs['msg'] = '操作失败';
        $data = $request->all();
       // dd($data);
        $wechat_user =  session('wechat.oauth_user.default'); 
        $user = User::where('openid',$wechat_user->id)->first();
        $data['username'] = $user->username."($user->truenmae)";
        $flag = TaskRepo::refund($data);       
        if($flag['status']==true) {
            $rs['status'] = 'success';
            $rs['msg']    = '操作成功';
        }

        return back()->with('rs',$rs);
    }


}
